class Fasta_file:
    def __init__(self, filename, options='r+'):
        self.open(filename, options)
    def next(self):
        if self.options != 'w':
            self.seq = ''       
            self.seqname = self.currline[1:len(self.currline)]
            while self.currline != '':
                self.seq += self.currline
                self.currline = self.file.readline()
                if self.currline == '' or self.currline[0] == '>':
                    break
            if self.seq != '' and self.seqname != '':
                return True
            else:
                return False
        else:
            print 'Cannot read from write-only file: '+self.file.name
    
    def write(self, seqname, seq):
        if self.currline != '':
            print 'Warning, you are about to overwrite content!'
        self.file.write('>'+seqname+'\n'+seq+'\n')
    
    def close(self):
        file.close()
    
    def open(self, filename, options='rw'):
        self.options = options
        self.file = open(filename, options)
        if self.options != 'w':
            self.currline = self.file.readline()
            if self.currline[0] != '>':
                raise Invalid_format, 'File '+filename+' has an invalid fasta format'
        else:
            self.currline = ''
        
class Invalid_format(Exception):
    pass